package com.neusoft.neuiotms.dcom.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.QQuestionnaire;
import com.neusoft.neuiotms.dcom.model.Questionnaire;
import com.neusoft.neuiotms.dcom.model.enums.QuestionnaireScope;
import com.neusoft.neuiotms.dcom.repository.CustomizedQuestionnaireRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedQuestionnaireRepositoryImpl extends AbstractRepository
        implements CustomizedQuestionnaireRepository {

    @Override
    public List<Questionnaire> index(final Searchable searchable) {
        final QQuestionnaire qQuestionnaire = QQuestionnaire.questionnaire;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Questionnaire> query = this.query().selectFrom(qQuestionnaire);
        query.where(where);
        return query.fetch();
    }

    @Override
    protected Class<?> getModelClass() {
        return Questionnaire.class;
    }

    @Override
    public Page<Questionnaire> search(final Pageable pageable, final Searchable searchable) {
        final QQuestionnaire qQuestionnaire = QQuestionnaire.questionnaire;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Questionnaire> query = this.query().selectFrom(qQuestionnaire);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {

        final BooleanBuilder where = new BooleanBuilder();
        final QQuestionnaire qQuestionnaire = QQuestionnaire.questionnaire;
        //用途
        if (!StringUtils.isEmpty(searchable.getStrValue("scope"))) {
            where.and((super.equalsEnum(qQuestionnaire.scope, searchable, "scope",
                    value -> QuestionnaireScope.valueOf(value))));
        }
        // 标题检索
        if (!StringUtils.isEmpty(searchable.getStrValue("title"))) {
            where.and(super.containsStr(qQuestionnaire.title, searchable, "title"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("groupCode"))) {
            where.and(super.containsStr(qQuestionnaire.groupCode, searchable, "groupCode"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("published"))) {
            where.and(super.equalsBool(qQuestionnaire.published, searchable, "published"));
        }
        if (null != searchable.getLongValue("closedAt")) {
            where.and(super.afterOrEqualsDate(qQuestionnaire.closedAt, searchable, "closedAt"));

        }

        return where;
    }
}
